package com.ruoyi.index.userController;

import com.ruoyi.chat.domain.FhChatFriend;
import com.ruoyi.chat.service.IFhChatFriendService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.index.domain.*;
import com.ruoyi.index.service.IFhIndexHotService;
import com.ruoyi.index.service.IFhIndexLikeService;
import com.ruoyi.index.service.IFhIndexPostcommentsService;
import com.ruoyi.index.service.IFhIndexPostinfoService;
import com.ruoyi.info.domain.*;
import com.ruoyi.info.service.*;
import com.ruoyi.map.domain.FhMapFishtype;
import com.ruoyi.map.service.IFhMapFishtypeService;
import com.ruoyi.tokenTools.UserLoginToken;
import com.test.aop.UserThreadLocal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 发布信息Controller
 *
 * @author ruoyi
 * @date 2024-11-11
 */
@Api(tags = "首页接口")
@RestController
@RequestMapping("/index/userPostinfo")
public class UserFhIndexPostinfoController extends BaseController {
    @Autowired
    private IFhIndexPostinfoService fhIndexPostinfoService;

    @Autowired
    private IFhIndexPostcommentsService iFhIndexPostcommentsService;

    @Autowired
    private IFhIndexLikeService iFhIndexLikeService;

    @Autowired
    private IFhChatFriendService iFhChatFriendService;

    @Autowired
    private IFhIndexHotService iFhIndexHotService;

    @Autowired
    private IFhInfoUserService fhInfoUserService;

    @Autowired
    private IFhInfoCatchrecordService fhInfoCatchrecordService;

    @Autowired
    private IFhInfoMyspaceService fhInfoMyspaceService;

    @Autowired
    private IFhInfoExperienceService fhInfoExperienceService;

    @Autowired
    private IFhMapFishtypeService fhMapFishtypeService;

    @Autowired
    private IFhInfoUsertaskService fhInfoUsertaskService;


    /**
     * 首页推荐列表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("首页推荐列表查询")
    @GetMapping("/indexList")
    public R<List<IndexInfoListVo>> list(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        try {
            startPage();
            //查询发布信息列表
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            List<FhIndexPostinfo> fhIndexPostinfoList = fhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            //通过发布信息列表，获得返回数据列表
            List<IndexInfoListVo> indexInfoListVoList = selectPostInfo(fhIndexPostinfoList);
            return R.ok(indexInfoListVoList);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 首页关注推荐列表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("首页关注列表查询")
    @GetMapping("/indexFollowList")
    public R<List<IndexInfoListVo>> indexFollowList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "5") int pageSize) {
        try {
            Long userId = UserThreadLocal.getUser();
            //根据用户id查询关注列表,
            FhChatFriend fhChatFriend = new FhChatFriend();
            fhChatFriend.setUserId(userId);
            List<FhChatFriend> fhChatFriendList = iFhChatFriendService.selectFhChatFriendList(fhChatFriend);
            Long[] friends = new Long[100];
            for (int i = 0; i < fhChatFriendList.size(); i++) {
                friends[i] = fhChatFriendList.get(i).getFriendId();
            }
            startPage();
            //根据好友id数组，以及时间倒序查询捕获表
            List<FhIndexPostinfo> fhIndexPostinfoList = fhIndexPostinfoService.selectFhIndexPostinfoListByIds(friends);
            List<IndexInfoListVo> indexInfoListVoList = selectPostInfo(fhIndexPostinfoList);
            return R.ok(indexInfoListVoList);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 首页附近列表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("首页附近列表查询")
    @GetMapping("/indexNearbyList")
    public R<List<IndexInfoListVo>> indexNearbyList(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "5") int pageSize,
                                                    String longitude,
                                                    String latitude
    ) {
        try {
            startPage();
            //根据经度，纬度查询捕获表
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setLongitude(longitude);
            fhIndexPostinfo.setLatitude(latitude);
            List<FhIndexPostinfo> fhIndexPostinfoList = fhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            List<IndexInfoListVo> indexInfoListVoList = selectPostInfo(fhIndexPostinfoList);
            return R.ok(indexInfoListVoList);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 返回用户发布信息列表方法
     */
    public List<IndexInfoListVo> selectPostInfo(List<FhIndexPostinfo> fhIndexPostinfoList) {
        //返回的数据
        List<IndexInfoListVo> indexInfoListVoList = new ArrayList<>();

        for (int i = 0; i < fhIndexPostinfoList.size(); i++) {
            //获取发布信息id
            Long postId = fhIndexPostinfoList.get(i).getId();
            IndexInfoListVo indexInfoListVo = new IndexInfoListVo();
            //插入发布信息
            indexInfoListVo.setFhIndexPostinfo(fhIndexPostinfoList.get(i));
            //插入发布鱼中名称
            String fishIds = fhIndexPostinfoList.get(i).getFishIds();
            String[] fishIdList = fishIds.split(",");
            String[] fishNameList = new String[fishIdList.length];
            for (int j = 0; j < fishIdList.length; j++) {
                Long fishId = Long.valueOf(fishIdList[j]);
                FhMapFishtype fhMapFishtype = fhMapFishtypeService.selectFhMapFishtypeById(fishId);
                fishNameList[j] = fhMapFishtype.getFishType();
            }
            String postInfoFishS = String.join(",", fishNameList);
            indexInfoListVo.setPostInfoFishS(postInfoFishS);
            //插入评论列表列表
            FhIndexPostcomments fhIndexPostcommen = new FhIndexPostcomments();
            fhIndexPostcommen.setPostinfoId(postId);
            List<FhIndexPostcomments> fhIndexPostcommentsList = iFhIndexPostcommentsService.selectFhIndexPostcommentsList(fhIndexPostcommen);
            indexInfoListVo.setFhIndexPostcommentsList(fhIndexPostcommentsList);

            //将添加完毕的数据放入返回体
            indexInfoListVoList.add(indexInfoListVo);
        }
        return indexInfoListVoList;
    }


    /**
     * 新增发布信息
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("发布")
    @PostMapping
    @Transactional
    public R<String> add(IndexInfoListDto indexInfoListDto) {
        try {
            Long userId = UserThreadLocal.getUser();
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(userId);
            //插入发布信息表数据
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setUserId(userId);
            fhIndexPostinfo.setUserName(fhInfoUser.getName());
            fhIndexPostinfo.setUserImage(fhInfoUser.getImage());
            fhIndexPostinfo.setUserLocation(fhInfoUser.getAddress());
            fhIndexPostinfo.setLongitude(indexInfoListDto.getLongitude());
            fhIndexPostinfo.setLatitude(indexInfoListDto.getLatitude());
            fhIndexPostinfo.setPostTime(new Date());
            fhIndexPostinfo.setHotWords(indexInfoListDto.getHotWords());
            fhIndexPostinfo.setPostText(indexInfoListDto.getPostText());
            fhIndexPostinfo.setLikes(0L);
            fhIndexPostinfo.setComments(0L);
            fhIndexPostinfo.setRetweets(0L);
            fhIndexPostinfo.setPostImages(indexInfoListDto.getFhIndexPostimageList());
            fhIndexPostinfo.setFishIds(indexInfoListDto.getFishIdList());
            FhIndexPostinfo fhIndexPostinfoResult = fhIndexPostinfoService.insertFhIndexPostinfo(fhIndexPostinfo);

            //修改个人信息渔获记录表，已抓渔获数，已抓渔获ids，已抓鱼钟数，已抓鱼钟ids，最常见鱼种id，最常见鱼种图片
            FhInfoCatchrecord fhInfoCatchrecord = fhInfoCatchrecordService.selectFhInfoCatchrecordByUserId(userId);
            //渔获数
            Long catchNum = fhInfoCatchrecord.getCatchNum();
            String[] fishIdList = indexInfoListDto.getFishIdList().split(",");
            catchNum += fishIdList.length;
            //渔获ids
            String catchNumids = fhInfoCatchrecord.getCatchNumids();
            String newCatchNumids;
            if (catchNumids == null|| catchNumids.isEmpty()) {
                newCatchNumids = indexInfoListDto.getFishIdList();
            } else {
                newCatchNumids = catchNumids + "," + indexInfoListDto.getFishIdList();
            }
            //计算已抓鱼种数,已抓鱼种ids
            String oldCatchTypeids = fhInfoCatchrecord.getCatchTypeids();
            String[] oldCatchTypeidList = oldCatchTypeids.split(",");
            //合并数组
            String[] newCatchTypeids = new String[oldCatchTypeidList.length + fishIdList.length];
            System.arraycopy(oldCatchTypeidList,0,newCatchTypeids,0,oldCatchTypeidList.length);
            System.arraycopy(fishIdList,0,newCatchTypeids,oldCatchTypeidList.length,fishIdList.length);
            //去重
            HashSet<String> set = new HashSet<>();
            for(String id : newCatchTypeids){
                set.add(id);
            }
            String[] result = new String[set.size()];
            int index =0;
            for(String id: set){
                result[index++] = id;
            }
            long catchTypeNum =(long) result.length;
            String catchTypeids = String.join(",",result);
            fhInfoCatchrecord.setCatchNum(catchNum);
            fhInfoCatchrecord.setCatchNumids(newCatchNumids);
            fhInfoCatchrecord.setCatchType(catchTypeNum);
            fhInfoCatchrecord.setCatchTypeids(catchTypeids);
            //查询最常见鱼类
            String[] newCatchNumidList = newCatchNumids.split(",");
            //计算该字符串中出现最多次数的元素
            String fishId = findMostFrequentChar(newCatchNumidList);
            long l = Long.parseLong(fishId);
            FhMapFishtype fhMapFishtype = fhMapFishtypeService.selectFhMapFishtypeById(l);
            fhInfoCatchrecord.setCommonFishid(l);
            fhInfoCatchrecord.setCommonFishimage(fhMapFishtype.getFishImage());
            fhInfoCatchrecordService.updateFhInfoCatchrecord(fhInfoCatchrecord);

            //修改我的空间发布数量
            FhInfoMyspace fhInfoMyspace = new FhInfoMyspace();
            fhInfoMyspace.setUserId(userId);
            List<FhInfoMyspace> fhInfoMyspaces = fhInfoMyspaceService.selectFhInfoMyspaceList(fhInfoMyspace);
            Long postNum = fhInfoMyspaces.get(0).getPostNum();
            postNum += 1;
            fhInfoMyspaces.get(0).setPostNum(postNum);
            fhInfoMyspaceService.updateFhInfoMyspace(fhInfoMyspaces.get(0));

            //修改发布渔获任务完成状态
            compleTask(1L);

            return R.ok("发布成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    //查找字符串数组中出现次数最多的字符串
    public static String findMostFrequentChar(String[] array) {
        Map<String, Integer> stringCountMap = new HashMap<>();
        for (String str : array) {
            stringCountMap.put(str, stringCountMap.getOrDefault(str, 0) + 1);
        }
        String mostFrequentString = null;
        int maxCount = 0;
        for (Map.Entry<String, Integer> entry : stringCountMap.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxCount = entry.getValue();
                mostFrequentString = entry.getKey();
            }
        }
        return mostFrequentString;
    }

    /**
     * 点赞发布信息
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("点赞发布信息")
    @PostMapping("/isLike")
    public R<String> isLike(Long postInfoId) {
        try {
            Long userId = UserThreadLocal.getUser();
            FhIndexLike fhIndexLike = new FhIndexLike();
            fhIndexLike.setUserId(userId);
            fhIndexLike.setPostinfoId(postInfoId);
            //插入点赞表
            iFhIndexLikeService.insertFhIndexLike(fhIndexLike);
            //修改发布信息点赞数
            FhIndexPostinfo fhIndexPostinfo = fhIndexPostinfoService.selectFhIndexPostinfoById(postInfoId);
            Long likes = fhIndexPostinfo.getLikes();
            likes += 1;
            fhIndexPostinfo.setLikes(likes);
            fhIndexPostinfoService.updateFhIndexPostinfo(fhIndexPostinfo);
            return R.ok("点赞成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 取消点赞发布信息
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("删除点赞发布信息")
    @DeleteMapping("/noLike")
    public R<String> noLike(Long postInfoId) {
        try {
            Long userId = UserThreadLocal.getUser();
            FhIndexLike fhIndexLike = new FhIndexLike();
            fhIndexLike.setUserId(userId);
            fhIndexLike.setPostinfoId(postInfoId);
            Long id = iFhIndexLikeService.selectFhIndexLikeList(fhIndexLike).get(0).getId();
            iFhIndexLikeService.deleteFhIndexLikeById(id);
            //修改发布信息点赞数
            FhIndexPostinfo fhIndexPostinfo = fhIndexPostinfoService.selectFhIndexPostinfoById(postInfoId);
            Long likes = fhIndexPostinfo.getLikes();
            likes -= 1;
            fhIndexPostinfo.setLikes(likes);
            fhIndexPostinfoService.updateFhIndexPostinfo(fhIndexPostinfo);
            return R.ok("取消点赞成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    /**
     * 发布评论
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("发布评论")
    @PostMapping("/postComment")
    @Transactional
    public R<String> postComment(FhIndexPostcomments fhIndexPostcomments) {
        try {
            Long userId = UserThreadLocal.getUser();
            //修改发布信息评论数量
            Long postinfoId = fhIndexPostcomments.getPostinfoId();
            FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
            fhIndexPostinfo.setId(postinfoId);
            List<FhIndexPostinfo> fhIndexPostinfos = fhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
            Long comments = fhIndexPostinfos.get(0).getComments();
            comments += 1;
            fhIndexPostinfos.get(0).setComments(comments);
            fhIndexPostinfoService.updateFhIndexPostinfo(fhIndexPostinfos.get(0));
            //发布评论
            fhIndexPostcomments.setCommentId(userId);
            fhIndexPostcomments.setCrateTime(new Date());
            iFhIndexPostcommentsService.insertFhIndexPostcomments(fhIndexPostcomments);

            //发布评论成功后增加发布用户经验,如果用户经验超过10，则升一级
            FhInfoUser fhInfoUser = fhInfoUserService.selectFhInfoUserByUserId(fhIndexPostcomments.getUserId());
            Long experience = fhInfoUser.getExperience();
            Long grade = fhInfoUser.getGrade();
            experience += 1;

            Long nextGrade = grade + 1;
            FhInfoExperience fhInfoExperience = fhInfoExperienceService.selectFhInfoExperienceById(nextGrade);
            Long experienceMax = fhInfoExperience.getExperienceMax();
            if (experience >= experienceMax) {
                grade += 1L;
                experience = 0L;
            }
            fhInfoUser.setExperience(experience);
            fhInfoUser.setGrade(grade);
            fhInfoUserService.updateFhInfoUser(fhInfoUser);

            //修改发布评论任务完成状态
            compleTask(3L);

            return R.ok("发布评论成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }

    }

    /**
     * 用户完成任务加积分
     */
    public R<String> compleTask(Long taskId)
    {
        try {
            //修改信息表
            Long userId = UserThreadLocal.getUser();
            FhInfoUser fhInfoUserInfo = fhInfoUserService.selectFhInfoUserByUserId(userId);
            Long points = fhInfoUserInfo.getPoints();
            points+=10;
            fhInfoUserInfo.setPoints(points);
            fhInfoUserService.updateFhInfoUser(fhInfoUserInfo);
            //修改任务表状态，1为未完成，0为完成
            FhInfoUsertask fhInfoUsertask = new FhInfoUsertask();
            fhInfoUsertask.setUserId(userId);
            fhInfoUsertask.setTaskId(taskId);
            fhInfoUsertask.setCompletionStatus("0");
            fhInfoUsertaskService.updateFhInfoUsertaskByUserIdAndTaskId(fhInfoUsertask);
            return R.ok("完成成功");
        }catch (Exception e){
            System.out.println(e.getMessage());
            return R.fail(e.getMessage());
        }
    }

    //定时更新热点表，每小时更新一次
    @Scheduled(cron = "0 0 0/1 * * ?")
//    @Scheduled(cron ="0/1 0 * * * ?")
    public void timedUpdateHot() {
        FhIndexPostinfo fhIndexPostinfo = new FhIndexPostinfo();
        List<FhIndexPostinfo> fhIndexPostinfos = fhIndexPostinfoService.selectFhIndexPostinfoList(fhIndexPostinfo);
        //List接口自身的sort方法对对象集合排序，重写Comparator接口方法即可
        fhIndexPostinfos.sort(new Comparator<FhIndexPostinfo>() {
            @Override
            public int compare(FhIndexPostinfo post1, FhIndexPostinfo post2) {
                Long likes1 = post1.getLikes();
                Long likes2 = post2.getLikes();
                return likes1.compareTo(likes2);
            }
        });
        //清空热点表数据
        FhIndexHot fhIndexHot = new FhIndexHot();
        List<FhIndexHot> fhIndexHots = iFhIndexHotService.selectFhIndexHotList(fhIndexHot);
        Long[] ids = new Long[50];
        for (int i = 0; i < fhIndexHots.size(); i++) {
            ids[i] = fhIndexHots.get(i).getId();
        }
        iFhIndexHotService.deleteFhIndexHotByIds(ids);
        //向热点表插入数据
        int i = fhIndexPostinfos.size();
        if (i > 20) {
            for (int i1 = i - 1; i1 >= i - 20; i1--) {
                if (fhIndexPostinfos.get(i1).getHotWords() == null) {
                    continue;
                }
                fhIndexHot.setPostinfoId(fhIndexPostinfos.get(i1).getId());
                fhIndexHot.setLikeNum(fhIndexPostinfos.get(i1).getLikes());
                fhIndexHot.setHotWords(fhIndexPostinfos.get(i1).getHotWords());
                iFhIndexHotService.insertFhIndexHot(fhIndexHot);
            }
        } else {
            for (int i1 = i - 1; i1 >= 0; i1--) {
                if (fhIndexPostinfos.get(i1).getHotWords() == null) {
                    continue;
                }
                fhIndexHot.setPostinfoId(fhIndexPostinfos.get(i1).getId());
                fhIndexHot.setLikeNum(fhIndexPostinfos.get(i1).getLikes());
                fhIndexHot.setHotWords(fhIndexPostinfos.get(i1).getHotWords());
                iFhIndexHotService.insertFhIndexHot(fhIndexHot);
            }
        }
    }

    /**
     * 首页热点表
     */
    @Anonymous
    @UserLoginToken
    @ApiOperation("获取热点表")
    @GetMapping("/hotList")
    public R<List<FhIndexHot>> hotList() {
        try {
            FhIndexHot fhIndexHot = new FhIndexHot();
            List<FhIndexHot> fhIndexHots = iFhIndexHotService.selectFhIndexHotList(fhIndexHot);
            fhIndexHots.sort(new Comparator<FhIndexHot>() {
                @Override
                public int compare(FhIndexHot o1, FhIndexHot o2) {
                    Long likeNum1 = o1.getLikeNum();
                    Long likeNum2 = o2.getLikeNum();
                    return likeNum2.compareTo(likeNum1);
                }
            });
            return R.ok(fhIndexHots);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


}
